import { reactive } from 'vue'
import type { FormRules } from 'element-plus'
import type { IAddUserFormType } from '@/typings/usersType'
import { checkUserNameApi } from '@/api/usersApi'

// 自定义验证规则
const checkUserName = (rule: any, value: string, callback: any) => {
  checkUserNameApi(value)
    .then(ret => {
      if (ret.data === 0) {
        callback()
      } else {
        callback(new Error('账号已存在'))
      }
    })
    .catch(() => {
      callback(new Error('远程验证异常'))
    })
}

export const useAddValidate = () => {
  const rules = reactive<FormRules<IAddUserFormType>>({
    realname: [
      { required: true, whitespace: true, message: '不能为空' },
      // 自定义验证
      { validator: checkUserName, trigger: 'blur' }
    ],
    userid: [{ required: true, whitespace: true, message: '不能为空' }],
    // password: [{ required: true, whitespace: true, message: '不能为空' }]
  })

  return rules
}
